package trackListGenerator;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;
import javax.imageio.ImageIO;

/**
 *
 * @author Aderthad
 */
public class ImgurUploader2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        upload(new File("d:\\Aderthad\\Wallpapers\\Cat and Balloon.jpg"));
    }

    public static void upload(File imageToUpload) {
        String IMGUR_POST_URI = "https://api.imgur.com/3/image";

        try {
            BufferedImage image = ImageIO.read(imageToUpload);

            byte[] imageInByte = null;
  
            System.out.println("Writing image...");
            
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                ImageIO.write(image, "jpg", baos);
                baos.flush();
                imageInByte = baos.toByteArray();
            }          

            URL url = new URL(IMGUR_POST_URI);
            System.out.println("Encoding...");

            String data = "image=" + URLEncoder.encode(Base64.encode(imageInByte), "UTF-8");

            System.out.println("Connecting...");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setRequestProperty("Authorization", "Client-ID 8a05c8b972acba3");

            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            System.out.println("Sending data...");
            wr.write(data);
            wr.flush();
            wr.close();
            System.out.println("Finished.");            
           
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getResponseMessage());
            
            InputStream is = conn.getInputStream();
            
            String response = "";
            
            StringBuilder sb = new StringBuilder();
            
            Scanner sc = new Scanner(is);
            while(sc.hasNext()){
                sb.append(sc.next());
            }
            response = sb.toString();
            
            System.out.println(response);
            
            conn.disconnect();

        } catch (IOException e) {
            System.out.println("ERROR " + e.getMessage());
        }
    }

}
